package com.after.saas.gateway.filter;

import com.after.saas.common.annotation.Log;
import com.after.saas.common.utils.ResponseUtil;
import com.after.saas.gateway.config.RequestListConfig;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Classname AuthFilter
 * @Description 黑名单过滤器
 * @Date 2021/7/17 14:03
 * @Created by hjchen
 */

@Slf4j
@Component
public class BlackListUrlFilter extends AbstractGatewayFilterFactory<Object> {

    @Autowired
    private RequestListConfig requestListConfig;

    @Override
    public GatewayFilter apply(Object config) {
        List<String> blackList = requestListConfig.getBlackList();
        return (exchange, chain) -> {
            String url = exchange.getRequest().getURI().getPath();
            if (requestListConfig.isMatched(blackList, url)) {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(ResponseUtil.FAILURE("请求地址不允许访问")))));
            }
            return chain.filter(exchange);
        };
    }

}
